/**
 * @class dataform-boots.js
 * @author jiagui E-mail:<zhujiagui@zkingsoft.com>
 * @date 2015年7月13日 上午11:04:55
 * @description 基于bootstrap样式，对表单等数据的处理进行封装调用
 */
(function($) {
	function DataForm() {
		this.obj = null;
		this.map = {};
	}
	$
			.extend(
					DataForm.prototype,
					{
						saveData : function(opts) {// 保存数据
							var formId = opts.formId;
							var form = opts.form;
							if (form == null || form == undefined) {
								if (formId != null && formId != undefined) {
									form = $("#form");
								} else {
									form = $($("body").find("form")[0]);
								}
							}
							if (form == null || form == undefined) {
								return;
							}
							var changedParam = "changedList";// 接收改变的表单数据的参数名
							var param = form.attr("changedParam");
							if (param != null && param != undefined
									&& param != "") {
								changedParam = param;
							}
							form
									.bootstrapValidator()
									.on(
											'success.form.bv',
											function(e) {
												e.preventDefault();
												if (opts.beforsubmit != null
														&& opts.beforsubmit != undefined) {
													// 获取表单提交按钮的可用状态
													opts.beforsubmit(opts);// 表单验证通过，提交之前
												}
												/*$btools.blockUI({
													msg : "正在提交数据，请稍候..."
												});*/
												$.ajax({
															cache : true,
															type : "POST",
															url : form
																	.attr('action'),
															data : form
																	.serialize()
																	+ "&"
																	+ $.form
																			.serializeChanged(
																					$.form
																							.getchangedProperties(),
																					changedParam),
															error : function(
																	request) {
																$btools
																		.alert(
																				"请求出错咯咯~",
																				function() {
																					/*$btools.unblockUI();// 隐藏加载提示框
*/																				});
																return;
															},
															success : function(
																	data) {
																/*$btools.unblockUI();// 隐藏加载提示框
*/																if (opts.onSaveSuccess != null
																		&& opts.onSaveSuccess != undefined) {
																	opts.data = data;
																	opts
																			.onSaveSuccess(opts);
																} else {
																	var msg = "操作失败！";
																	var code = null;
																	var shortCutFunction = "info";
																	if (data != null) {
																		code = data.code;
																		var remsg = data.result["msg"];
																		if (code == "true") {
																			shortCutFunction = "success";
																			if (remsg != null
																					&& remsg != undefined) {
																				msg = remsg;
																				//$btools.showToast({msg:msg});
																				$btools.showToast({
																					msg : msg,
																					shortCutFunction : "success",
																					positionClass : "toast-center-center",
																				});
																			} else {
																				msg = "操作成功！";
																			}
																		} else if (code == "false") {
																			shortCutFunction = "warning";
																			if (remsg != null
																					&& remsg != undefined) {
																				msg = remsg;
																			} else {
																				msg = "操作失败！";
																			}
																		} else if (code == "error") {
																			shortCutFunction = "error";
																			if (remsg != null
																					&& remsg != undefined) {
																				msg = remsg;
																			} else {
																				msg = "操作异常！";
																			}
																		}else if (code == "info") {
																			shortCutFunction = "info";
																			if (remsg != null
																					&& remsg != undefined) {
																				msg = remsg;
																			} else {
																				msg = "无需保存！";
																			}
																		}
																	}
																	
																	if (opts.savesuccess != null
																			&& opts.savesuccess != undefined) {// 保存方法执行完成之后
																		opts.code = code;
																		opts.msg = msg;
																		opts.form = form;
																		opts.shortCutFunction = shortCutFunction;
																		opts
																				.savesuccess(opts);
																	} else {
																		/* $btools.alert(msg); */
																		$btools.showToast({
																					msg : msg,
																					shortCutFunction : shortCutFunction
																				});
																	}
																}
															}
														});
											});
						},
						setData : function(options) {
							var defaults = {
								formId : "",
								form : null,
								data : null
							};
							var opts = $.extend(defaults, options);
							var form = opts.form;
							var data = opts.data;
							var formId = opts.formId;
							if (form == null || form == undefined) {
								if (formId == null || formId == undefined
										|| formId == "") {
									form = $($("body").find("form")[0]);
								} else {
									form = $("#" + formId);
								}
							}
							if (form != null && form != undefined
									&& data != null && data != undefined) {
								$.form.obj = data;
								var inputs = form.find("input,textarea,select");
								if (inputs != null && inputs.length > 0) {
									inputs
											.each(function(index) {
												if ($(this).attr("name") != undefined) {
													for ( var name in data) {
														if (name == $(this)
																.attr("name")) {
															if (this.className
																	.indexOf("bootselect") >= 0) {
																$btools
																		.selectItem({
																			obj : $(this),
																			data : data[name]
																		});
															} else {
																this.value = data[name];
															}
															continue;
														}
													}
												}
											});
								}
							}
							if (opts.ondataload != null
									&& opts.ondataload != undefined) {
								opts.ondataload(opts);// 数据加载完成事件
							}
						},
						showedit : function(options) {
							//alert("调用了showedit！");
							var defaults = {
								primarykey : null,
								dataUrl : "",
								formId : "",
								paramName : "key"
							};
							var opts = $.extend(defaults, options);
							 //$btools.loadingshow("正在获取数据，请稍候..."+opts.dataUrl);
							/*$btools.blockUI({
								msg : "正在获取数据，请稍候..."
							});*/
							$.ajax({
								cache : true,
								type : "POST",
								url : opts.dataUrl,
								data : opts.paramName + "=" + opts.primarykey,
								error : function(request) {
									alert("请求出错~");
									return;
								},
								success : function(data) {
									//$btools.unblockUI();// 隐藏加载提示框
									var msg = null;
									if (data != null) {
										if (data.code == "true") {// 数据加载成功
											if (data.result["obj"] != null) {
												opts.data = data.result["obj"];
												//alert("opts.data"+opts.data);
												$.form.setData(opts);// 设置数据到表单
												$.form.loadFormSuccess(opts);// 表单数据加载完成后执行
											} else {
												msg = "数据为空!";
											}
										} else if (data.code == "error") {
											if (data.result["msg"] != null) {
												msg = data.result["msg"];
											} else {
												msg = "数据查询失败!";
											}
										} else {
											msg = "操作失败！";
										}
									} else {
										msg = "数据加载失败！";
									}
									if (msg != null) {
										$btools.alert(msg);
									}
								}
							});
						},
						submitForm : function(opt) {
							opt.form.find("button[type='submit']")[0].click();// 提交数据
						},
						getchangedProperties : function() {
							var changedList = [];
							for ( var name in $.form.map) {
								changedList.push($.form.map[name]);
							}
							return changedList;
						},
						serializeChanged : function(changedList, param) {
							var serialize = "";
							if (changedList != null && changedList.length > 0) {
								for (var i = 0, a = changedList.length; i < a; i++) {
									serialize += param + "[" + i + "].field="
											+ changedList[i].field + "&"
											+ param + "[" + i
											+ "].beforeChange="
											+ changedList[i].beforeChange + "&"
											+ param + "[" + i
											+ "].afterChange="
											+ changedList[i].afterChange;
									if (i < changedList.length - 1) {
										serialize += "&";
									}
								}
							}
							return serialize;
						},
						loadFormSuccess : function() { // 表单数据加载完成后执行
						}
					});
	$.form = new DataForm();
	$(document)
			.ready(
					function() {
						var changedProperties = null;// 记录表单属性的修改状况
						var _this = null;
						var beforeChange = null;
						var value = null;
						var fieldName = null;
						var field = null;
						$("form :input,textarea,select")
								.change(
										function() {
											_this = $(this);
											fieldName = _this.attr("for-name");
											field = this.name;
											if ($.form.obj != null) {
												value = this.value;
												if (field) {
													if (this.className
															.indexOf("bootselect") >= 0) {
														var values = [];
														_this
																.children(
																		"option:selected")
																.each(
																		function(
																				index,
																				e) {
																			values
																					.push($(
																							e)
																							.attr(
																									"value"));
																		});
														value = values
																.join(",");
													}
													beforeChange = $.form.obj[field];
												}
												if (beforeChange != null
														&& beforeChange != undefined) {
													if (value != beforeChange) {
														if (fieldName == null
																|| fieldName == undefined) {
															fieldName = field;
														}
														changedProperties = {};
														changedProperties.name = fieldName;
														changedProperties.field = field;
														changedProperties.beforeChange = beforeChange;
														changedProperties.afterChange = value;
														$.form.map[field] = changedProperties;
													} else {
														if (field in $.form.map) {
															delete $.form.map[field];
														}
													}
												}
											}
										});
					});
})(jQuery);